<template>
  <div class="freight-forwarder-content">
    <!-- 子标签页 -->
    <div class="sub-tabs">
      <span
          v-for="(tab, index) in subTabs"
          :key="index"
          :class="{ 'active': activeSubTab === tab }"
          @click="setActiveSubTab(tab)"
      >
        {{ subTabsDisplay[index] }}
      </span>
    </div>

    <!-- 子标签页内容 -->
    <component
        :is="currentSubComponent"
        :businessId="getCurrentBusinessId"
        :freightForwarderData="localFreightForwarderData"
        @update:freightForwarderData="updateFreightForwarderData"
    ></component>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useShippingRateStore } from '../shippingRateStore'
import AirFreightContent from './AirFreightContent.vue'
import FCLFreightContent from './FCLFreightContent.vue'
import LCLFreightContent from './LCLFreightContent.vue'
import OrgPortChargesContent from './OrgPortChargesContent.vue'
import DstPortChargesContent from './DstPortChargesContent.vue'
import { createNewBusiness, createNewFeeRecord } from './createBusinessRecords.js'

export default {
  name: 'FreightForwarderContent',
  components: {
    AirFreightContent,
    FCLFreightContent,
    LCLFreightContent,
    OrgPortChargesContent,
    DstPortChargesContent
  },
  props: {
    freightForwarderData: {
      type: Object,
      required: true,
      default: () => ({
        business: []
      })
    }
  },
  emits: ['update:freightForwarderData'],
  setup(props) {//, { emit }
    const store = useShippingRateStore()

    const activeSubTab = ref('air')
    const subTabs = ['air', 'fcl', 'lcl', 'originPortCharges', 'destinationPortCharges']
    const subTabsDisplay = ['空运', 'FCL运费', 'LCL/FTL/TL/COU Freight', '起运港费用', '目的港费用']

    const localFreightForwarderData = ref(initializeFreightForwarderData(props.freightForwarderData))
    const onCalculatorDataChange = (data) => {
      console.log('Calculator data changed:', data);
      // 在这里处理计算器数据变化
    };

    const currentSubComponent = computed(() => {
      const componentMap = {
        air: AirFreightContent,
        fcl: FCLFreightContent,
        lcl: LCLFreightContent,
        originPortCharges: OrgPortChargesContent,
        destinationPortCharges: DstPortChargesContent
      }
      return componentMap[activeSubTab.value]
    })

    const setActiveSubTab = (tab) => {
      activeSubTab.value = tab
    }

    const getCurrentBusinessId = computed(() => {
      if (!localFreightForwarderData.value || !localFreightForwarderData.value[activeSubTab.value]) {
        console.warn(`FreightForwarderData or its ${activeSubTab.value} property is not properly initialized`);
        return `new-${activeSubTab.value}-${Date.now()}`;
      }
      const currentBusiness = localFreightForwarderData.value[activeSubTab.value].find(b => b.businessType === activeSubTab.value);
      return currentBusiness?.id || `new-${activeSubTab.value}-${Date.now()}`;
    });
    const updateFreightForwarderData = (updatedData, source = 'local') => {
      console.log(`FreightForwarderContent: Updating data from ${source}`, updatedData);

      if (source === 'api') {
        // API 数据更新
        localFreightForwarderData.value = {
          ...localFreightForwarderData.value,
          ...updatedData,
          _dataSource: 'api'
        };
      } else {
        // 本地数据更新（来自子组件）
        let lastUpdatedIndex = -1;
        let lastUpdatedBusinessType = '';
        console.log('updatedData:', updatedData);
        updatedData.forEach(newData => {
          const { businessType, id } = newData;
          lastUpdatedBusinessType = businessType;
          // 确保 businessType 对应的属性存在且是一个数组
          if (!Array.isArray(localFreightForwarderData.value[businessType])) {
            localFreightForwarderData.value[businessType] = [];
          }

          const index = localFreightForwarderData.value[businessType].findIndex(item => item.id === id);
          lastUpdatedIndex = index;
          if (index !== -1) {
            // 更新现有对象
            localFreightForwarderData.value[businessType][index] = {
              ...localFreightForwarderData.value[businessType][index],
              ...newData
            };





          } else {
            const emptyIdIndex = localFreightForwarderData.value[businessType].findIndex(item => item.id === '');
            if (emptyIdIndex !== -1) {
              // 更新 ID 为空的记录
              localFreightForwarderData.value[businessType][emptyIdIndex] = {
                ...localFreightForwarderData.value[businessType][emptyIdIndex],
                ...newData
              };
              lastUpdatedIndex = emptyIdIndex;
            } else {
              // 如果没有 ID 为空的记录，则添加新对象
              localFreightForwarderData.value[businessType].push(newData);
              lastUpdatedIndex = localFreightForwarderData.value[businessType].length - 1;
            }
          }
        });

        console.log('更新后的 localFreightForwarderData:', localFreightForwarderData.value);

        const businessArray = localFreightForwarderData.value[lastUpdatedBusinessType];

        console.log('businessArray:', businessArray);
        localFreightForwarderData.value = {
          ...localFreightForwarderData.value,
          _dataSource: 'local'
        };
        const hasEmptyIdRow = businessArray.some(row => row.id === '');

        if (!hasEmptyIdRow) {
          const newRow = createNewBusiness("",lastUpdatedBusinessType)
          newRow.businessType=lastUpdatedBusinessType;
          localFreightForwarderData.value[lastUpdatedBusinessType].push(newRow)
          console.log('Created new record for row:', localFreightForwarderData)
        } else {
          console.log('Skipped creating new row: Empty id row already exists')
        }






        const currentBusiness = businessArray[lastUpdatedIndex !== -1 ? lastUpdatedIndex : businessArray.length - 1];
        ensureFeeTable(currentBusiness);
      }
      // 确保 feeTable 存在并且只有一个空记录


      console.log('Updated FreightForwarderData:', JSON.parse(JSON.stringify(localFreightForwarderData.value)));
     /// emit('update:freightForwarderData', localFreightForwarderData.value);
    };

    function initializeFreightForwarderData(data) {
      if (!data || typeof data !== 'object') {
        return {};
      }
      const initializedData = {};
      subTabs.forEach(tab => {
        initializedData[tab] = Array.isArray(data[tab]) ? data[tab] : [];
      });
      return initializedData;
    }

    const ensureFeeTable = (business) => {
      if (!Array.isArray(business.feeTable)) {
        business.feeTable = [];
      }
      const emptyRowIndex = business.feeTable.findIndex(isRowEmpty);
      if (emptyRowIndex === -1) {
        business.feeTable.push(createNewFeeRecord(business.id));
      } else if (emptyRowIndex < business.feeTable.length - 1) {
        business.feeTable = business.feeTable.slice(0, emptyRowIndex + 1);
      }
    };

    const isRowEmpty = (row) => {
      const fieldsToIgnore = ['id', 'parentId'];
      return Object.entries(row).every(([key, value]) => {
        if (fieldsToIgnore.includes(key)) {
          return true;
        }
        return value === '' || value === null || value === undefined ||
            (typeof value === 'object' && Object.keys(value).length === 0);
      });
    };



    watch(() => props.freightForwarderData, (newVal) => {
      localFreightForwarderData.value = initializeFreightForwarderData(newVal);
    }, { deep: true });

    return {
      onCalculatorDataChange,
      activeSubTab,
      subTabs,
      subTabsDisplay,
      currentSubComponent,
      setActiveSubTab,
      getCurrentBusinessId,
      store,


      updateFreightForwarderData,
      localFreightForwarderData
    }
  }
}
</script>

<style scoped>
.freight-forwarder-content {
  font-family: Arial, sans-serif;
}

.sub-tabs {
  display: flex;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ccc;
  margin-bottom: 1px;
}

.sub-tabs span {
  padding: 8px 12px;
  cursor: pointer;
  border: 1px solid transparent;
  border-bottom: none;
  margin-bottom: 0;
}

.sub-tabs span.active {
  background-color: #fff;
  border-color: #ccc;
  border-bottom-color: #fff;
}

.calculator-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
}

:deep(.v-select) {
  width: 100%;
}
</style>
